package Filter;

import model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检测用户是否登录并别是管理员
 */
@WebFilter(filterName = "UserLoginFilter", value = "/admin/*")
public class UserLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取用户
        User user = (User) req.getSession().getAttribute("user");
        String path = req.getContextPath();
        //用户登录了并且是管理员
        if (user != null && user.isIsadmin()) {
            chain.doFilter(request, response);
        } else if (user == null) { //没登录
            resp.sendRedirect(path + "/user_login.jsp");
        } else {    //登录了但是不是管理员
            resp.sendRedirect(path + "/index");
        }
    }
}

